import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'
import { getToken } from '@/utils/cookies'
import { isNotEmpty } from '@/utils/validate'

const TOKEN_HEADER = "authorization";

// create an axios instance
const axiosService = axios.create({
    // url = base url + request url
    baseURL: process.env.VUE_APP_SERVERAPI,
    // send cookies when cross-domain requests
    withCredentials: true
    // request timeout
    // timeout: 5000
})

axiosService.interceptors.request.use(config => {
        let token = getToken()
        if (isNotEmpty(token)) {
            config.headers[TOKEN_HEADER] = token
        }else{
            if (!config.url.endsWith('/login')) {
                Message({ message: '登录过期', type: 'warning', duration: 5000 })
                store.commit('LOGOUT')
                location.reload()
            }
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

// response interceptor
axiosService.interceptors.response.use(response => {

        if (isNotEmpty(response.headers[TOKEN_HEADER])) {
            store.commit('SET_TOKEN', response.headers[TOKEN_HEADER])
            return response.data
        } else if (response.data.code !== 200) {
            Message({ message: response.data.msg, type: 'error', duration: 5000 })
            if (response.data.code === 401) {
                store.commit('LOGOUT')
                location.reload()
            } else {
                return response
            }
        } else {
            return response.data
        }
    },
    error => {
        Message({ message: error.message, type: 'error', duration: 5000 })
        return Promise.reject(error)
    }
)

export const postFormRequest = (url, params) => {
    return axiosService({
        method: 'post',
        url: `${url}`,
        data: params,
        transformRequest: [function(data) {
            let ret = ''
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            return ret
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
}

export const putFormRequest = (url, params) => {
    return axiosService({
        method: 'put',
        url: `${url}`,
        data: params,
        transformRequest: [function(data) {
            let ret = ''
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            return ret
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
}

export const uploadFileRequest = (url, params) => {
    return axiosService({
        method: 'post',
        url: `${url}`,
        params: params
    })
}

export const exportExcelGet = (url, params, filename = Date.now().toString()) => {
    return axiosService({
        method: 'get',
        url: `${url}`,
        params: params,
        responseType: 'blob'
    }).then(res => {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = URL.createObjectURL(res)
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })
}

export const exportExcelPost = (url, params, filename = Date.now().toString()) => {
    return axiosService({
        method: 'post',
        url: `${url}`,
        data: params,
        responseType: 'blob',
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(res => {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = URL.createObjectURL(res)
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })
}

export const deleteRequest = (url, params) => {
    return axiosService({
        method: 'delete',
        url: `${url}`,
        params: params
    })
}

export const postRequest = (url, params) => {
    return axiosService({
        method: 'post',
        url: `${url}`,
        data: params,
        headers: {
            'Content-Type': 'application/json'
        }
    })
}

export const putRequest = (url, params) => {
    return axiosService({
        method: 'put',
        url: `${url}`,
        data: params,
        headers: {
            'Content-Type': 'application/json'
        }
    })
}

export const getRequest = (url, params) => {
    return axiosService({
        method: 'get',
        url: `${url}`,
        params: params
    })
}


